package cn.devzyh.oms.wsms.service.impl;

import cn.devzyh.oms.common.core.constant.CommonConstants;
import cn.devzyh.oms.wsms.api.entity.SkuItem;
import cn.devzyh.oms.wsms.mapper.SkuItemMapper;
import cn.devzyh.oms.wsms.service.SkuItemService;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SkuItemServiceImpl extends ServiceImpl<SkuItemMapper, SkuItem> implements SkuItemService {

	@Override
	public List<Tree<Long>> treeMenu(Long parentId, String itemName) {
		Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;

		List<TreeNode<Long>> collect = baseMapper
				.selectList(Wrappers.<SkuItem>lambdaQuery()
						.like(StrUtil.isNotBlank(itemName), SkuItem::getName, itemName)
						.orderByAsc(SkuItem::getSortOrder))
				.stream()
				.map(getNodeFunction())
				.collect(Collectors.toList());

		// 模糊查询 不组装树结构 直接返回 表格方便编辑
		if (StrUtil.isNotBlank(itemName)) {
			return collect.stream().map(node -> {
				Tree<Long> tree = new Tree<>();
				tree.putAll(node.getExtra());
				BeanUtils.copyProperties(node, tree);
				return tree;
			}).collect(Collectors.toList());
		}

		return TreeUtil.build(collect, parent);
	}

	@NotNull
	private Function<SkuItem, TreeNode<Long>> getNodeFunction() {
		return menu -> {
			TreeNode<Long> node = new TreeNode<>();
			node.setId(menu.getId());
			node.setName(menu.getName());
			node.setParentId(menu.getParentId());
			node.setWeight(menu.getSortOrder());
			// 扩展属性
			Map<String, Object> extra = new HashMap<>();
			extra.put("sortOrder", menu.getSortOrder());
			node.setExtra(extra);
			return node;
		};
	}

}